package com.burningtower.controller;

import com.burningtower.Enum.GoodsEnum;
import com.burningtower.common.Pages;
import com.burningtower.common.Result;
import com.burningtower.entity.*;
import com.burningtower.service.*;
import com.burningtower.vo.OrderVo;
import com.burningtower.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/6.
 */
@RestController
@RequestMapping("manage")
public class ManageController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;

    /**
     * 无条件分页查
     * @param session
     * @param datagridReq
     * @return Pages<ProductVo>
     */
    @RequestMapping("product/list.do")
    public DatagridResult<Product> list(HttpSession session,DatagridReq datagridReq){

        Pages<Product> page = productService.adminSearch( session,new Product(), datagridReq.getSort()+"_"+datagridReq.getOrder(),  datagridReq.getPage(),  datagridReq.getRows());//执行查询
        DatagridResult<Product> result=new DatagridResult<>();
        result.setRows(page.getList());
        System.out.println(page.getPageNum());
        System.out.println(page.getPageSize());
        System.out.println(page.getPages());

        result.setTotal(page.getTotal());
        return  result;
    }

    /**
     *  有条件分页查
     *  @param session
     *  @param pageNum
     *  @param pageSize
     *  @param productId
     *  @param productName
     *  @param orderBy
     *  @return Pages<ProductVo>
     */
    @RequestMapping("product/search.do")
    public Result<Pages<Product>> search(HttpSession session,Integer productId, String productName, String orderBy,
                                    //如果传入当前页数是null，对其初始化
                                    @RequestParam(required = false, defaultValue = "1")Integer pageNum,
                                    //如果传入size是null，对其初始化
                                    @RequestParam(required = false, defaultValue = "10") Integer pageSize){

        Product product=new Product();
        product.setId(productId);
        product.setName(productName);
        Pages<Product> page = productService.adminSearch(session, product, orderBy,  pageNum,  pageSize);//执行查询

        Result<Pages<Product>> result = new Result<>();
        result.setData(page);
        result.setStatus(0);
        return  result;
    }

    /**
     * 上传图片
     * @param multipartFile
     * @return Result
     */
    @RequestMapping("product/upload.do")
    public Result upload(@RequestParam(name = "upload_file")MultipartFile multipartFile) throws IOException {
        String path="C:/Users/zhuhaier/IdeaProjects/HappyMall/src/main/resources/static/upload/";
        //TODO 判断文件属性
        String uri=System.currentTimeMillis()+multipartFile.getOriginalFilename();
        multipartFile.transferTo(new File(path,uri));

        String url=path+uri;
        System.out.println(url);
        Map map = new HashMap();
        map.put("url",url);
        map.put("uri",uri);

        Result<Map> result=new Result<>();
        result.setData(map);
        result.setStatus(0);
        return result;
    }

    /**
     * 根据productId查询
     * @param productId
     * @return Result<Product>
     */
    @RequestMapping("product/detail.do")
    public Result<Product> get(Integer productId){
        Product product = productService.get(productId);
        Result<Product> result = new Result<>();
        result.setStatus(0);
        result.setData(product);
        return result;
    }

    /**
     * 新增产品
     * @param product
     * @return AjaxResult
     */
    @RequestMapping("product/save.do")
    public AjaxResult save(Product product){
        Result<String> result = productService.add(product);
        AjaxResult ajaxResult=result.getStatus()==0?new AjaxResult(GoodsEnum.INSERT_SUC):new AjaxResult(GoodsEnum.INSERT_FAIL);
        return ajaxResult;
    }
    /**
     *  修改产品
     *  @param product
     *  @return AjaxResult
     */
    @RequestMapping("product/update.do")
    public AjaxResult update(@RequestBody Product product){
        Result<String> result=productService.update(product);
        AjaxResult ajaxResult=result.getStatus()==0?new AjaxResult(GoodsEnum.UPDATE_SUCCESS):new AjaxResult(GoodsEnum.UPDATE_ERROR);
        return ajaxResult;
    }

    /**
     * 修改产品状态
     * @param productId
     * @param status
     * @return Result<String>
     */
    @RequestMapping("product/set_sale_status.do")
    public Result<String> changeStatus(Integer productId,Integer status){
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        Result<String> result = productService.updateStatus(product);
        return result;

    }

    /**
     * 富文本上传图片
     * @param multipartFile
     * @return Result
     */
    @RequestMapping("product/richtext_img_upload.do")
    public Result uploadrich(@RequestParam(name = "upload_file")MultipartFile multipartFile) throws IOException {
        // 判断文件属性
        String fileName = multipartFile.getOriginalFilename();
        fileName.lastIndexOf(".");
        String s = fileName.substring(fileName.lastIndexOf("."));
        if (!s.equals("jpg")&&!s.equals("bmp")&&!s.equals("gif")){
            throw new RuntimeException();
        }
        String uri=System.currentTimeMillis()+fileName;
        multipartFile.transferTo(new File("http://img.happymmall.com/",uri));//把这个文件存到这个地址 TODO 有问题啊！
        Result<Map> result=new Result<>();
        String file_path="http://img.happymmall.com/"+uri;
        Map map = new HashMap();
        map.put("file_path",file_path);
        map.put("success",true);
        result.setData(map);
        result.setMsg("上传成功");
        return result;
    }

    /**
     * 获取品类子节点(平级)
     * @param session
     * @param categoryId
     * @return Result<List<Category>>
     */
    @RequestMapping("category/get_category.do")
    public Result<List<Category>> getCategory(HttpSession session,Integer categoryId)  {
        if(session.getAttribute("userId")==null){
            throw new RuntimeException("用户未登录,请登录");
        }
        Result<List<Category>> result = categoryService.getListById(categoryId);
        return result;
    }

    /**
     * 增加节点
     * @param parentId
     * @param categoryName
     * @return Result<String>
     */
    @RequestMapping("category/add_category.do")
    public Result<String> addCategory(@RequestParam(required = false,defaultValue = "0") Integer parentId,String categoryName)  {
        Result<String> result = categoryService.add(parentId, categoryName);
        return result;
    }

    /**
     * 修改品类名字
     * @param categoryId
     * @param categoryName
     * @return Result<String>
     */
    @RequestMapping("category/set_category_name.do")
    public Result<String> updateCategory(Integer categoryId,String categoryName)  {
        Result<String> result = categoryService.update(categoryId, categoryName);
        return result;
    }

    /**
     * 获取当前分类id及递归子节点categoryId
     * @param categoryId
     * @return Result<Integer[]>
     */
    @RequestMapping("category/get_deep_category.do")
    public Result<Integer[]> getDeepById(Integer categoryId)  {
        Result<Integer[]> result = categoryService.getDeepById(categoryId);
        return result;
    }

    /**
     * 后台管理员登录
     * @param username
     * @param password
     * @return Result<UserVo>
     */
    @RequestMapping("user/login.do")
    public Result<UserVo> login(HttpSession session,String username,String password){
        User user = userService.login(username, password);
        if(user==null){
            throw new RuntimeException("密码错误");
        }
        if(user.getRole()!=0){
            throw new RuntimeException("没有权限");
        }
        session.setAttribute("userId",user.getId());

        Result<UserVo> result = new Result<>();
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        result.setData(userVo);
        result.setStatus(0);
        return result;
    }

    /**
     * 返回所有
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("order/list.do")
    public Result<Pages<OrderVo>> orderList(@RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                            @RequestParam(required = false,defaultValue = "10") Integer pageSize){
        Result<Pages<OrderVo>> result=new Result<>();
        Pages<OrderVo> pages = orderService.getPages(pageNum, pageSize, "createTime_desc");

        result.setStatus(0);
        result.setData(pages);
        return result;
    }

    @RequestMapping("order/search.do")
    public Result<Pages<OrderVo>> search(Long orderNo,
                                         @RequestParam(required = false,defaultValue = "createTime_desc")String orderBy,
                                         @RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                         @RequestParam(required = false,defaultValue = "10") Integer pageSize){
        Result<Pages<OrderVo>> result=new Result<>();
        Pages<OrderVo> pages = orderService.getPagesByOrderNo(orderNo,pageNum, pageSize,orderBy);

        result.setStatus(0);
        result.setData(pages);
        return result;
    }
}
